import React, { useState, useEffect } from 'react';
import { Button, Modal, Form, Input, InputNumber, message, Card, Popconfirm } from 'antd';
import { PlusOutlined, DragOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors } from '@dnd-kit/core';
import { arrayMove, SortableContext, sortableKeyboardCoordinates, verticalListSortingStrategy } from '@dnd-kit/sortable';
import { useSortable } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { Column } from '@/types/content';
import { contentService } from '@/services/contentService';

// 可拖拽的栏目项组件
const SortableColumnItem = ({ column, onEdit, onDelete }: { 
  column: Column; 
  onEdit: (col: Column) => void; 
  onDelete: (id: number) => void; 
}) => {
  const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ id: column.id });
  const style = { transform: CSS.Transform.toString(transform), transition };

  return (
    <div ref={setNodeRef} style={style} {...attributes}>
      <div 
        style={{ 
          padding: '12px', 
          border: '1px solid #d9d9d9', 
          borderRadius: '6px', 
          marginBottom: '8px', 
          backgroundColor: '#fff',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between'
        }}
      >
        <div 
          style={{ 
            display: 'flex', 
            alignItems: 'center', 
            flex: 1,
            cursor: 'grab',
            userSelect: 'none'
          }}
          {...listeners}
        >
          <DragOutlined style={{ marginRight: 8, color: '#999' }} />
          <div>
            <div style={{ fontWeight: 'bold' }}>{column.name}</div>
            {column.description && <div style={{ fontSize: '12px', color: '#666' }}>{column.description}</div>}
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <EditOutlined 
            style={{ color: '#1890ff', cursor: 'pointer' }} 
            onClick={() => onEdit(column)} 
          />
          <Popconfirm 
            title="确定删除该栏目吗？" 
            onConfirm={() => onDelete(column.id)}
          >
            <DeleteOutlined 
              style={{ color: '#ff4d4f', cursor: 'pointer' }} 
            />
          </Popconfirm>
        </div>
      </div>
    </div>
  );
};

interface ColumnManagerProps {
  columns: Column[];
  onColumnsChange: (columns: Column[]) => void;
  onRefresh: () => void;
}

const ColumnManager: React.FC<ColumnManagerProps> = ({ columns, onColumnsChange, onRefresh }) => {
  const [modalVisible, setModalVisible] = useState(false);
  const [editingColumn, setEditingColumn] = useState<Column | null>(null);
  const [form] = Form.useForm();

  // 当模态框打开时，根据编辑状态设置表单值
  useEffect(() => {
    if (modalVisible) {
      if (editingColumn) {
        form.setFieldsValue(editingColumn);
      } else {
        form.resetFields();
      }
    }
  }, [modalVisible, editingColumn, form]);

  const sensors = useSensors(
    useSensor(PointerSensor),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates,
    })
  );

  const handleAddColumn = () => {
    setEditingColumn(null);
    setModalVisible(true);
  };

  const handleEditColumn = (col: Column) => {
    setEditingColumn(col);
    setModalVisible(true);
  };

  const handleDeleteColumn = async (id: number) => {
    try {
      await contentService.deleteColumn(id);
      message.success('删除成功');
      onRefresh();
    } catch {
      message.error('删除失败');
    }
  };

  const handleColumnOk = async () => {
    try {
      const values = await form.validateFields();
      if (editingColumn) {
        await contentService.updateColumn(editingColumn.id, values);
        message.success('修改成功');
      } else {
        await contentService.createColumn(values);
        message.success('新建成功');
      }
      setModalVisible(false);
      onRefresh();
    } catch {}
  };

  const handleDragEnd = async (event: any) => {
    const { active, over } = event;
    
    if (active.id !== over.id) {
      const oldIndex = columns.findIndex(col => col.id === active.id);
      const newIndex = columns.findIndex(col => col.id === over.id);
      const newColumns = arrayMove(columns, oldIndex, newIndex);
      
      // 更新本地状态
      onColumnsChange(newColumns);
      
      // 调用API更新栏目顺序
      try {
        const updatePromises = newColumns.map((col, index) => 
          contentService.updateColumn(col.id, { ...col, order: index + 1 })
        );
        await Promise.all(updatePromises);
        message.success('排序更新成功');
      } catch (error) {
        message.error('排序更新失败');
        // 如果API调用失败，重新获取数据
        onRefresh();
      }
    }
  };

  return (
    <>
      <div style={{ marginBottom: 16 }}>
        <Button type="primary" icon={<PlusOutlined />} onClick={handleAddColumn}>新增栏目</Button>
      </div>
      <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
        <SortableContext items={columns.map(col => col.id)} strategy={verticalListSortingStrategy}>
          {columns.map(column => (
            <SortableColumnItem
              key={column.id}
              column={column}
              onEdit={handleEditColumn}
              onDelete={handleDeleteColumn}
            />
          ))}
        </SortableContext>
      </DndContext>

      <Modal
        title={editingColumn ? '编辑栏目' : '新建栏目'}
        open={modalVisible}
        onOk={handleColumnOk}
        onCancel={() => setModalVisible(false)}
        destroyOnClose
      >
        <Form form={form} layout="vertical">
          <Form.Item name="name" label="栏目名称" rules={[{ required: true, message: '请输入栏目名称' }]}> 
            <Input maxLength={20} />
          </Form.Item>
          <Form.Item name="description" label="描述">
            <Input.TextArea maxLength={100} rows={2} />
          </Form.Item>
          <Form.Item name="order" label="排序">
            <InputNumber min={1} style={{ width: '100%' }} />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default ColumnManager; 